package cn.xxd.xxdssoservice.service;

import cn.xxd.common.JsonUtils;
import cn.xxd.common.RedisConstants;
import cn.xxd.entity.LoginUser;
import cn.xxd.entity.ReturnT;
import cn.xxd.entity.ShopUser;
import cn.xxd.xxdssointerface.LoginService;
import cn.xxd.xxdssoservice.dao.LoginUserDao;
import cn.xxd.xxdssoservice.dao.ShopUserDao;
import cn.xxd.xxdssoservice.util.RedisUtil;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

@Service(version = "1.0.0", interfaceClass = LoginService.class)
public class LoginServiceImpl implements LoginService {

    @Autowired
    private LoginUserDao loginUserDao;

    @Autowired
    private ShopUserDao shopUserDao;

    @Autowired
    private RedisUtil redisUtil;

    @Value("${SESSION_EXPIRE}")
    private Integer SESSION_EXPIRE;

    @Override
    public ReturnT login(LoginUser loginUser) {
        loginUser.setPassword(DigestUtils.md5DigestAsHex(loginUser.getPassword().getBytes()));
        //判断账号密码
        LoginUser user = loginUserDao.checkUser(loginUser);
        if (user == null) {
            return new ReturnT(400, "账号或密码错误!");
        }
        ShopUser shopUser = shopUserDao.getShopUserByUserId(String.valueOf(user.getId())); // 登录用户Id
        // String token = UUID.randomUUID().toString();
        //  把用户信息写入redis，
        user.setPassword(null);
        try {
            redisUtil.set("SSO:" + shopUser.getId(), JsonUtils.objectToJson(user), RedisConstants.datebase0);
            // 设置Session的过期时间
            redisUtil.expire("SSO:" + shopUser.getId(), 60, RedisConstants.datebase0); //设置key过期时间
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ReturnT("SSO:" + shopUser.getId());
    }

    @Override
    public LoginUser getMsg(String username, String name) {
        LoginUser user = loginUserDao.getMsg(username, name);
        return user;
    }

    @Override
    public LoginUser getMsgById(String id) {
        LoginUser user = loginUserDao.getMsgById(id);
        return user;
    }

    @Override
    public ReturnT logOut(String token) {
        return null;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ReturnT edit(ShopUser user) {
        try {
            loginUserDao.edit(user);
        } catch (Exception e) {
            return new ReturnT(500, "failed");
        }
        return new ReturnT(200, "success");
    }


}
